package spring.cloud.eurekaclientproduct.cmd;

import com.netflix.hystrix.HystrixObservableCommand;
import com.spring.cloud.commonutils.vo.ResultMessage;
import org.springframework.web.client.RestTemplate;
import rx.Observable;
import rx.Subscriber;

public class UserExpCommand extends HystrixObservableCommand<ResultMessage> {

    private RestTemplate restTemplate;
    private String[] params = null;

    private final String url = "http://eureka-client-user/exp/{msg}";

    public UserExpCommand(Setter setter,RestTemplate restTemplate, String[] params) {
        super(setter);
        this.restTemplate = restTemplate;
        this.params = params;

    }

    @Override
    protected Observable<ResultMessage> construct() {
        Observable.OnSubscribe<ResultMessage>subs = (Subscriber<? super ResultMessage> resSubs)->{
            try{
                int count = 0;
                if(!resSubs.isUnsubscribed()){
                    for(String param:params){
                        count ++;
                        System.out.println("第【"+count+"】次发送");
                        ResultMessage resMsg = restTemplate.getForObject(url,ResultMessage.class,param);
                        resSubs.onNext(resMsg);
                    }
                    resSubs.onCompleted();
                }
            }catch (Exception ex){
                resSubs.onError(ex);
            }
        };
        return Observable.unsafeCreate(subs);
    }

    @Override
    protected Observable<ResultMessage> resumeWithFallback() {
        return Observable.error(new RuntimeException("发生了异常"));
    }
}
